<?php

/* ----------------------------------------------
  Caloris: Module Modules

  $Id$
  $Author$

  List of all modules with editor
  ---------------------------------------------- */

require_once("../../../index.php");
Caloris\ACL::authenticate();

define('_MODULE_ACTIVE', 'modulemanager');

$urlExtensions = _CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/extensions.xml';

if ($_REQUEST["function_name"] == 'module_install') {
    $type = $_REQUEST["type"];


    if ($type == 'transfer') {
        $modulenm = strtolower(substr($_REQUEST['file'], 0, -4));
        $folders = _CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/' . strtolower($_REQUEST['file']);
    } else {
        $modulenm = strtolower(substr($_FILES['the_file']['name'], 0, -4));
        $folders = _CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/' . strtolower($_FILES['the_file']['name']);
    }

    // Checks permissions
    if (!Caloris\ACL::authorize("modules") == 1) {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Nemáte oprávnění"));
        exit();
    }

    // Checks whether the module exists
    if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . substr($modulenm, 11))) {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Modul s tímto názvem již existuje"));
        exit();
    }

    $xmlModulesCheck = new Caloris\XML();
    $xmlModulesCheck->source(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/modules.xml');
    $xmlModulesCheck->filter('//module[@id="' . substr($modulenm, 11) . '"]');

    if (count($xmlModulesCheck->output) > 0) {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Modul s tímto názvem již existuje"));
        exit();
    }

    // Copy the compressed file to its place
    if ($type != 'transfer') {
        if ($_FILES['the_file']['name'] <> "none") {
            if (!copy($_FILES['the_file']['tmp_name'], $folders)) {
                header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Upload ZIPu modulu selhal"));
                exit();
            } else {
                chmod($folders, 0777);
            }
        }
    }

    // Extracts the compressed file
    $zip = new ZipArchive;
    if ($zip->open($folders) === true) {
        $zip->extractTo(_CALSET_PATHS_BASE);
        $zip->close();
    } else {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Extrakce ZIPu modulu selhala"));
        exit();
    }


    // Loads xml file
    $xmlModulesF = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/module-' . substr($modulenm, 11) . '.xml');
    $xmlModules = $xmlModulesF->xpath('//module');

    // Writes extension module and editing rights, md5
    $extensionDirectory = explode(";", $xmlModules[0]->list_extensions);

    for ($a = 0; $a < count($extensionDirectory); $a++) {
        $extensionNameNoExt = substr($extensionDirectory[$a], 0, -4);
        $extensionFileName = $extensionDirectory[$a];

        if ($extensionDirectory[$a] == '.' or $extensionDirectory[$a] == '..') {
            
        } else {
            // Search for existence of extensions in extensions directory. Deletes records in XML file for non-existing extensions, adds XML descriptions for extension files
            $xmlExtensionsCheckF = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/extensions.xml');
            $xmlExtensionsCheck = $xmlExtensionsCheckF->xpath('//extension[@id="' . $extensionNameNoExt . '"]');

            if (count($xmlExtensionsCheck) == 0) {

                $filein = Caloris\IO::get(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $extensionFileName);
                $startin = strpos($filein, "/*");
                $endin = strpos($filein, "*/");
                $descriptor = explode(":", substr($filein, ($startin + 2), (($endin - $startin)) - 2));

                // Find the comment section of the extension
                $extensionPositionStart .= strpos($filein, '<extension');
                $extensionPositionEnd .= strpos($filein, '</extension>') + 12;
                $extensionXmlString = html_entity_decode(substr($filein, $extensionPositionStart, ($extensionPositionEnd - $extensionPositionStart)), 0, 'UTF-8');
                $extensionXml = simplexml_load_string($extensionXmlString);

                if (count($extensionXml)) {
                    $extensionName = $extensionXml[0]["id"];
                    $extensionAuthor = $extensionXml[0]->author;
                    $extensionDescription = $extensionXml[0]->description;
                    $extensionModule = $extensionXml[0]->modules->name;
                } else {
                    $extensionName = $extensionFileName;
                    $extensionAuthor = '';
                    $extensionDescription = $descriptor[1];
                    $extensionModule = '';
                }

                $extension = simplexml_load_file($urlExtensions);

                $xt = $extension->AddChild("extension");
                $xt["id"] = $extensionName;
                $xt->author = $extensionAuthor;
                $xt->description = $extensionDescription;

                if (count($extensionModule) > 0) {
                    $md = $xt->AddChild("modules");

                    for ($c = 0; $c < count($extensionModule); $c++) {
                        $md->name[] = $extensionModule[$c];
                    }
                }

                $extension->asXML($urlExtensions);
            }
        }

        unset($extensionNameNoExt);
    }

    // Setting imformation to modules XML file
    $moduleAdd = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/modules.xml');

    $moduleSet = $moduleAdd->modules->AddChild("module");
    $moduleSet["id"] = substr($modulenm, 11);
    $moduleSet->name = substr($modulenm, 11);

    $xmlModulesAddF = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/module-' . substr($modulenm, 11) . '.xml');
    $xmlModulesAdd = $xmlModulesAddF->xpath('//module');

    foreach ($xmlModulesAdd[0] as $key => $node) {
        $moduleSet->{$key} = $node;
    }

    $moduleAdd->asXML(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/modules.xml');

    // SQL install
    if (strlen($xmlModules->output[0]->install_sql) > 4 && _CALSET_DATABASE_ADDRESS != '') {
        $sqlcode = file_get_contents(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . substr($modulenm, 11) . '/' . $xmlModules->output[0]->install_sql);
        $module_sql = new Caloris\Database();
        $module_sql->query($sqlcode);
    }

    // Deleting XML settings
    if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/' . $modulenm . ".zip")) {
        unlink(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/' . $modulenm . ".zip");
    }

    // Deleting module information XML file
    if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/module-' . substr($modulenm, 11) . '.xml')) {
        unlink(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/module-' . substr($modulenm, 11) . '.xml');
    }

    // Renaming htaccess file if present
    if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/'. substr($modulenm, 11) . '/htaccess.txt')) {
        rename(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/'. substr($modulenm, 11) . '/htaccess.txt', _CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/'. substr($modulenm, 11) . '/.htaccess');
    }

    // Redirecting to Administrator homepage or modules page
    if (strlen($xmlModules->output[0]->install_script) > 4) {
        if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . substr($modulenm, 11) . '/' . $xmlModules->output[0]->install_script)) {
            header("location: " . _CALSET_PATHS_URI . '/cal-components/modules/' . substr($modulenm, 11) . '/' . $xmlModules->output[0]->install_script);
            exit();
        } else {
            if ($xmlModules->output[0]->hasadmin == 1) {
                header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . substr($modulenm, 11) . '/index.php');
                exit();
            } else {
                header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php");
                exit();
            }
        }
    } else {
        if ($xmlModules->output[0]->hasadmin == 1) {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . substr($modulenm, 11) . '/index.php');
            exit();
        } else {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php");
            exit();
        }
    }
} elseif ($_REQUEST["function_name"] == 'module_uninstall') {
    $modn = $_POST["name"]; // Module name

    $xmlExtensionDeleteF = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/modules.xml');
    $xmlExtensionDelete = $xmlExtensionDeleteF->xpath('//module[@id="' . strtolower($modn) . '"]');
    $listExtensions = explode(';', $xmlExtensionDelete[0]->list_extensions);

    if (!Caloris\ACL::authorize("modules") == 1) {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Nemáte oprávnění"));
        exit();
    }

    // Date checking
    if (strcmp($_POST["rand"], date("d.m.")) > 0) {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?id=" . $modn . "&msg=" . urlencode("Zadali jste nesprávné datum"));
        exit();
    }

    // Uninstalling SQL
    if (defined('_CALSET_MODULES_' . strtoupper($modn) . '_UNINSTALL_SQL')) {
        $uninstall_sql = constant('_CALSET_MODULES_' . strtoupper($modn) . '_UNINSTALL_SQL');
        if (strlen($uninstall_sql) > 4) {
            if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $modn . '/' . $uninstall_sql)) {
                $sqlcode = file_get_contents(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $modn . '/' . $uninstall_sql);
                $module_sql = new Caloris\Database();
                $module_sql->query($sqlcode);
            }
        }
    }

    // Deletes module directory
    if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $modn)) {
        $files1 = scandir(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $modn);
    }

    for ($a = 0; $a < count($files1); $a++) {
        if ($files1[$a] == '.' or $files1[$a] == '..') {
            
        } else {
            unlink(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $modn . '/' . $files1[$a]);
        }
    }

    if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $modn)) {
        rmdir(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $modn);
    }

    // Deletes extensions if permitted
    if ($_POST["del_ext"] == 1) {
        if (count($listExtensions) > 0) {
            for ($b = 0; $b < count($listExtensions); $b++) {
                if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $listExtensions[$b])) {
                    unlink(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $listExtensions[$b]);
                }

                // Delete records in XML extensions settings
                $fileName = _CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $listExtensions[$b] . '.php';


                // Deleting pages from pages.xml
                $doc = new DOMDOcument;
                $doc->load($urlExtensions);
                $xpath = new DOMXpath($doc);
                $query = '//extension[@id="' . $listExtensions[$b] . '"]';

                foreach ($xpath->query($query) as $node) {
                    $node->parentNode->removeChild($node);
                }

                $doc->save($urlExtensions);

                if (file_exists($fileName)) {
                    unlink($fileName);
                }
            }
        }
    }

    // Remove module description and settings from an XML settings
    $doc = new DOMDOcument;
    $doc->load(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/modules.xml');
    $xpath = new DOMXpath($doc);
    $query = '//module[@id="' . $modn . '"]';

    foreach ($xpath->query($query) as $node) {
        $node->parentNode->removeChild($node);
    }

    $doc->save(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/modules.xml');

    // Redirect back
    header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/administrator/index.php");
    exit();
}

$content = '
<h1>Moduly</h1>

<span style="color: red;">' . $_GET["msg"] . '</span>' . PHP_EOL;

if (Caloris\ACL::authorize("modules") == 1) {
    $content .= '
<h2>Nahrát modul</h2>

<form action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . _MODULE_ACTIVE . '/addons.modules.php" method="post" enctype="multipart/form-data">
<p><input type="hidden" name="function_name" value="module_install" /><input type="file" name="the_file" />&nbsp;<input type="submit" value="Instalovat" class="btn btn-primary" /></p>
</form>' . PHP_EOL;
}

// Lists modules
$xmlModulesF = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/modules.xml');
$xmlModules = $xmlModulesF->xpath('//module');

// sort by name
function sort_trees($t1, $t2) {
    return strcoll($t1["id"], $t2["id"]);
}

usort($xmlModules, 'sort_trees');

if (count($xmlModules) > 0) {
    $content .= '
<h2>Nainstalované moduly</h2>        

<table class="table table-striped">
    <tr>
        <th style="width: 70px;"></th>
        <th style="width: 200px;">Jméno modulu</th>
        <th>Popisek</th>
        <th>Detailní popis</th>
    </tr>
';
    for ($x = 0; $x < count($xmlModules); $x++) {
        if ($xmlModules[$x]->hasadmin == 1) {
            if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $xmlModules[$x]["id"] . '/index.html')) {
                $adminStartPage = '<a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . $xmlModules[$x]["id"] . '/index.html">Vstupte</a>';
            }

            if (file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_MODULE . '/' . $xmlModules[$x]["id"] . '/index.php')) {
                $adminStartPage = '<a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . $xmlModules[$x]["id"] . '/index.php">Vstupte</a>';
            }
        } else {
            $adminStartPage = '';
        }

        $content .= '
    <tr>
        <td>' . $adminStartPage . '</td>
        <td>' . $xmlModules[$x]->name . '</td>
        <td>' . $xmlModules[$x]->description . '</td>
        <td><a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . _MODULE_ACTIVE . '/addons.modules.detail.php?id=' . $xmlModules[$x]["id"] . '">Nastavení</a></td>
    </tr>';
    }

    $content .= '
</table>';
} else {
    $content .= '<p>Žádné moduly nenalezeny</p>';
}

$data["title"] = 'Moduly';

$tmpl = new Caloris\Template;
$tmpl->input($content);
$tmpl->renderHead($data);
echo $tmpl->renderBody('caloris-admin');